﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.SolverFoundation.Services;

namespace EmbeddedSharp.Scripting.Optimization
{
    public class OMLSolver {

        protected string template = @"
                Model [
                    Decisions [
                        Integers,
                        {0}
                    ],                    
                    Constraints [
                    {3}
                    ],
                    Goals[
                        {1}[{2}]
                    ]
                ]";

        public Solution Solve(
            string expr, bool type,
            string[] args, string[] constraints) {
            string a = Concat("", args);
            string c = Concat("", constraints);

            string model = string.Format(
                template, a, type ? "Maximize" : "Minimize",
                expr, c);

            SolverContext.GetContext().ClearModel();
            StringReader reader = new StringReader(model);
            SolverContext context = SolverContext.GetContext();
            context.LoadModel(FileFormat.OML, reader);
            return context.Solve();
        }

        private static string Concat(string prefix, string[] args) {
            StringBuilder buff = new StringBuilder();

            for (int index = 0; index < args.Length; index++) {
                if (!string.IsNullOrEmpty(prefix)) {
                    buff.Append(prefix).Append(index).Append(" -> ");
                }
                buff.Append(args[index]);
                if (index + 1 < args.Length) {
                    buff.Append(",");
                }
            }
            return buff.ToString();
        }
    }
}
